package 西交915编程题;

public class LCS {


    //最长公共子序列长度，（可以不连续）
    public static int lcs(String a, String b) {
        //动态规划
        int[][] dp = new int[a.length() + 1][b.length() + 1];
        for (int i = 1; i <= a.length(); i++) {
            for (int j = 1; j <= b.length(); j++) {
                if (a.charAt(i - 1) == b.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                else
                    dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
            }

        }
        //输出最长公共子序列，根据dp

        return dp[a.length()][b.length()];
    }

    //最长公共子串长度，（连续）
    public static int lcs2(String a, String b) {
        //动态规划
        int max = 0;
        int[][] dp = new int[a.length() + 1][b.length() + 1];
        for (int i = 1; i <= a.length(); i++) {
            for (int j = 1; j <= b.length(); j++) {
                if (a.charAt(i - 1) == b.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    max = Math.max(max, dp[i][j]);
                }
            }

        }
        //输出最长公共子串，根据dp


        return max;
    }

    public static void main(String[] args) {
        String a = "abcdef";
        String b = "cf";
        int[][] dp = new int[a.length()][b.length()];
        System.out.println(LCS.lcs(a, b));
        System.out.println(LCS.lcs2(a, b));

    }
}
